package com.base.cn.platform.os.controller.course.count;

import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.controller.BaseController;
import com.base.cn.platform.os.common.service.CommonSetSubjectDataService;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.http.HttpUtil;
import com.base.cn.platform.os.entity.course.count.ToLiveCount;
import com.base.cn.platform.os.entity.course.count.TopSubjectPlayCount;
import com.base.cn.platform.os.entity.manage.subject.SysSubject;
import com.base.cn.platform.os.service.course.cou.CourseBiz;
import com.base.cn.platform.os.service.course.cou.record.CoursePlayRecordBiz;
import com.base.cn.platform.os.service.course.material.CouMaterialBiz;
import com.base.cn.platform.os.service.manage.config.SysConfigService;
import com.base.cn.platform.os.service.manage.subject.SubjectService;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 课程统计Controller接口
 *
 * @author s.li
 * @create 2018-08-23-19:13query96KMonthDataCount
 */
@RestController
@RequestMapping("/course")
public class CourseCountController extends BaseController {
    @Autowired
    private CourseBiz courseBiz;
    @Autowired
    private CouMaterialBiz couMaterialBiz;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private CoursePlayRecordBiz coursePlayRecordBiz;
    @Autowired
    private SubjectService subjectService;
    @Autowired
    private CommonSetSubjectDataService commonSetSubjectDataService;

    /**
     * 查询课程统计数据
     * @return Map<String, Integer>
     */
    @RequestMapping("/queryCourseCountNum")
    public Map<String, Integer> queryCourseCountNum(){
        Map<String,Integer> courseNumMap = new HashMap<>();
        BigDecimal sumCourseNum = courseBiz.count(" courseTypeKey !='PACKAGE' and status!=3");
        BigDecimal liveNodeNum = couMaterialBiz.count(" typeKey='LIVE'");
        courseNumMap.put("sumCourseNum",sumCourseNum.intValue());
        courseNumMap.put("liveNodeNum",liveNodeNum.intValue());
        return courseNumMap;
    }

    /**
     * 获取视频与录播的数量
     * @return Map<String,Integer>
     */
    @RequestMapping("/queryVideoAndLiveNum")
    public Map<String,Integer> queryVideoAndLiveNum(){
        BigDecimal liveNodeNum = couMaterialBiz.count(" typeKey='LIVE'");
        BigDecimal videoNodeNum = couMaterialBiz.count(" typeKey='VIDEO'");
        Map<String,Integer> videoLiveNum = new HashMap<>();
        videoLiveNum.put("liveNodeNum",liveNodeNum.intValue());
        videoLiveNum.put("videoNodeNum",videoNodeNum.intValue());
        return videoLiveNum;
    }

    /**
     * 获取96K基本统计数据
     * @return Map<String,Object>
     */
    @RequestMapping("/get96KCountData")
    public Map<String,Object> get96KCountData()throws IOException {
        TreeMap<String,String> configMap = sysConfigService.getSysConfigContext(ConfigName.V96K);
        String serviceUrl = configMap.get("serviceUrl");
        String customerKey = configMap.get("customerKey");
        Map<String,String> params = new HashMap<>();
        params.put("customerKey",customerKey);
        String result = HttpUtil.doPost(serviceUrl,params);
        Map<String,Object> resultMap = null;
        if(StringUtils.isNotEmpty(result)){
            resultMap = gson.fromJson(result,new TypeToken<Map<String, Object>>(){}.getType());
        }
        if(ObjectUtils.isNotEmpty(resultMap)){
            String code = (String)resultMap.get("code");
            if(!"0".equals(code)){
                return null;
            }
            List<Map<String,Object>> dataList = (List<Map<String,Object>>)resultMap.get("data");
            if(ObjectUtils.isNotEmpty(dataList)){
                return dataList.get(0);
            }
        }
        return null;
    }

    /**
     * 获取96K当月观看流量曲线
     * @return List<Map<String,Object>>
     */
    @RequestMapping("/query96KMonthDataCount")
    public List<Map<String,Object>> query96KMonthDataCount(@RequestBody Map<String,String> maps) throws IOException, ParseException {
        TreeMap<String,String> configMap = sysConfigService.getSysConfigContext(ConfigName.V96K);
        Map<String,String> params = new HashMap<>();
        params.put("customerKey",configMap.get("customerKey"));
        //获取当前时间所在月份的第一天和最后一天
        String firstDay =maps.get("begTime");
        String lastDay =maps.get("endTime");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(StringUtils.isNotEmpty(firstDay)){
            firstDay = sdf2.format(sdf.parse(firstDay));
        }
        if(StringUtils.isNotEmpty(lastDay)){
            lastDay = sdf2.format(sdf.parse(lastDay));
        }
        if(StringUtils.isEmpty(maps.get("begTime"))&&StringUtils.isEmpty(maps.get("endTime"))){
            Map<String,String> dateMap = DateUtils.getMonthFirstLastData(DateUtils.format(new Date(),"yyyy-MM-dd"));
            firstDay = dateMap.get("firstDay");
            lastDay = dateMap.get("lastDay");
        }
        //获取前月的第一天
        Date _startTime = DateUtils.parseDate(firstDay,"yyyy-MM-dd HH:mm:ss");
        long startTime = _startTime.getTime()/1000L;

        //获取前月的最后一天
        Date _endTime = DateUtils.parseDate(lastDay,"yyyy-MM-dd HH:mm:ss");
        long endTime = _endTime.getTime()/1000L;

        params.put("startTime",String.valueOf(startTime));
        params.put("endTime",String.valueOf(endTime));
        String result = HttpUtil.doPost(configMap.get("serviceUseInfoUrl"),params);

        List<Map<String,Object>> dataList = null;
        if(StringUtils.isNotEmpty(result)){
            Map<String,Object> resultMap = gson.fromJson(result,new TypeToken<Map<String, Object>>(){}.getType());
            String code = (String)resultMap.get("code");
            if(!"0".equals(code)){
                return null;
            }
            dataList = (List<Map<String,Object>>)resultMap.get("data");
            if(ObjectUtils.isNotEmpty(dataList)){
                Map<String,Map<String,Object>> mapMap = dataList.stream().collect(Collectors.toMap(e->(String)e.get("time"), em->em));
                List<Date> dateList = DateUtils.getDayList(_startTime,_endTime);
                List<Map<String,Object>> resultMapList = new ArrayList<>();
                for(Date date : dateList){
                    String time = DateUtils.format(date,"yyyyMMdd");
                    String day = DateUtils.format(date,"dd");
                    Map<String,Object> map = mapMap.get(time);
                    if(ObjectUtils.isNotEmpty(map)){
                        map.put("day",day);
                        resultMapList.add(map);
                    }else{
                        Map<String,Object> _map = new HashMap<>();
                        _map.put("time",time);
                        _map.put("day",day);
                        _map.put("flow",0);
                        resultMapList.add(_map);
                    }
                }
                dataList = resultMapList;
            }
        }
        return dataList;
    }

    /**
     * 专业/科目观看量 TOP 10
     * @return List<TopSubjectPlayCount>
     */
    @RequestMapping("/queryTopSubjectPlayCount")
    public List<TopSubjectPlayCount> queryTopSubjectPlayCount(){
        List<TopSubjectPlayCount> topSubjectPlayCountList = coursePlayRecordBiz.queryTopSubjectPlayCount();
        if(ObjectUtils.isNotEmpty(topSubjectPlayCountList)){
            String subjectIds = commonSetSubjectDataService.getSubjectIds(topSubjectPlayCountList);
            Map<String,Object> params = new HashMap<>();
            params.put("queryIds",subjectIds);
            Map<BigDecimal, SysSubject> subjectMaps = subjectService.findSubjectToIdMap(params);
            if(ObjectUtils.isNotEmpty(subjectMaps)){
                topSubjectPlayCountList.forEach(e->{
                    List<SysSubject> subjectList = new ArrayList<>();
                    String _subjectIds = StringUtils.subHeadTailString(e.getSubjectIds(),",");
                    String[] arr = _subjectIds.split(",");
                    Arrays.stream(arr).forEach(id->{
                        SysSubject subject = subjectMaps.get(new BigDecimal(id));
                        if(ObjectUtils.isNotEmpty(subject)){
                            subjectList.add(subject);
                        }
                    });
                    e.setSubjectList(subjectList);
                });
            }
        }
        return topSubjectPlayCountList;
    }

    /**
     * 访问量最高的前 10场 直播
     * @return List<ToLiveCount>
     */
    @RequestMapping("/queryToLiveCount")
    public List<ToLiveCount> queryToLiveCount(){
        List<ToLiveCount> toLiveCountList = coursePlayRecordBiz.queryToLiveCount();
        return toLiveCountList;
    }
}
